package com.yunmaple.rabbitmq.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunmaple.rabbitmq.entity.Order;
import com.yunmaple.rabbitmq.mapper.OrderMapper;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalTime;

@Service
public class MessageServiceImpl {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderMapper orderMapper;

    public void sendMsg(String queueName, Order order) {
        LocalDate sdf = LocalDate.now();
        System.out.println("消息发送时间:" + sdf.getDayOfYear() + "年" + sdf.getMonthValue() + "月" + sdf.getDayOfMonth() + " " + LocalTime.now() + ".......===========发送的消息内容为：" + order);
        orderMapper.addOrderInfo(order);
        ObjectMapper mapper=new ObjectMapper();
        try {
            String message = mapper.writeValueAsString(order);
            rabbitTemplate.convertAndSend("test_exchange", queueName, message.getBytes(), new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    //设置延时消费时间（单位：秒）
                    message.getMessageProperties().setHeader("x-delay", order.getStoptime() * 1000 * 10);
                    return message;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}